import store from '@/store/index.js';
export const Audio = uni.createInnerAudioContext();
import {
	pubUrl
} from '@/api/http.js';

//
export let mp3Src =store.state.songSheet.list.length==0?"": pubUrl + store.state.songSheet.list[store.state.songSheet.playIndex].musicUrl
//播放音乐
export const playAudio = () => {
	Audio.play(); //执行播放
	store.commit('setPlayState', true)
}
//暂停音乐
export const pauseAudio = () => {
	Audio.pause(); //暂停播放
	store.commit('setPlayState', false)
}
//切换音乐
export const switchSong = (type, auto = false, index) => {
	if (type == 1) { //表示上一曲
		store.commit('upPlayIndex')
	} else if (type == 2) { //表示下一曲
		if (store.state.pattern.patternIndex == 1 && auto) { //表示播放器播放完，自动切换了歌曲，当前模式是单曲循环
			Audio.currentTime = 0; // 重新播放
			Audio.play();
			return;
		} else if (store.state.pattern.patternIndex == 2) { //表示手动切歌，当前模式随机播放模式
			store.commit('setPlayIndex', random(0, store.state.songSheet.list.length))
		} else { //其他手动切换歌曲
			store.commit('downPlayIndex')
		}
	} else if (type == 3) { //播放指定的歌曲
		store.commit('setPlayIndex', index)
	}
	mp3Src = pubUrl + store.state.songSheet.list[store.state.songSheet.playIndex].musicUrl
	Audio.src = mp3Src;
	Audio.play()
	store.commit('setPlayState', true)
}

//准备播放器
export const initAudio = () => {
	if (store.state.songSheet.list.length == 0) {
		return;
	}
	//自动播放
	Audio.autoplay = false;
	mp3Src = pubUrl + store.state.songSheet.list[store.state.songSheet.playIndex].musicUrl
	Audio.src = mp3Src; //音频地址
	//异常回调
	Audio.onError(res => {
		console.log(res.errMsg);
		console.log(res.errCode);
	});
	//暂停回调
	Audio.onPause(function() {
		//Audio.destroy();
	});
	//进度的回调
	Audio.onTimeUpdate(function() {
		// 	console.log(Audio.currentTime)
	})
}
initAudio()
//生产随机数 m-n,包括m不包括n
function random(m, n) {
	return Math.floor(Math.random() * (n - m)) + m
}
